﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Logger;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;

namespace DepartmentWork.Platform.Areas.DevelopArea.Controllers
{
    public class TaskBookController : BaseController
    {
        /// <summary>
        /// 任务书列表
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <returns></returns>
        public ActionResult ProjectTaskBookList(string projectId,string flag="",string flagInfo="")
        {
            Guid proId = new Guid(projectId);

            #region 设置分页

            var pageSize = this.Request["pageSize"] == null ? 10 : int.Parse(Request["pageSize"]);
            var pageIndex = this.Request["pageIndex"] == null ? 1 : int.Parse(Request["pageIndex"]);

            ViewData["pageIndex"] = pageIndex;
            ViewData["pageSize"] = pageSize;

            #endregion

            #region 校验该登录用户是否是项目负责人

            ViewBag.IsDevelopLeader = false;

            #region 原版

            //if (CurrentUser.UserID.Length != 0)
            //{
            //    Guid userGuid = new Guid(CurrentUser.UserID);
            //    USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            //    PROJECT_DEVELOP_USER developUser = projectDevelopUserRepository.GetModel(r => r.USER_ID == user.USER_ID && r.PROJECT_ID == proId).FirstOrDefault();
            //    if (developUser != null)
            //    {
            //        if (developUser.USER_POSITION == 1)
            //        {
            //            ViewBag.IsDevelopLeader = true;
            //        }
            //    }
            //}

            #endregion


            #region 改版后

            //1 、 获取当前用户所在角色
            //2. 获取该角色 所具有的 所有 权限
            //3. 确认该角色是否具有该权限
            Guid userGuid = new Guid(CurrentUser.UserID);
            USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
            USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();
            ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
            List<AUTHORITY_ROLE> authRoleList =
                authorityRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();



            for (int i = 0; i < authRoleList.Count; i++)
            {
                bool result = false;
                result =
                    empAuthorityRepository.GetModel(r => r.AUTHORITY_ID == authRoleList[i].AUTHORITY_ID)
                        .FirstOrDefault()
                        .AUTHORITY_TITLE.Contains("开发管理项目细节操作");
                if (result == true)
                {
                    ViewBag.IsDevelopLeader = true;
                    break;

                }
            }

            #endregion

            #endregion

            List<PROJECT_DEVELOP_TASKBOOK> taskBookList = projectDevelopTaskBookRepository.GetModel(r => r.PROJECT_ID == proId).OrderByDescending(r => r.CREATE_TIME).Take(pageSize * pageIndex).Skip(pageSize * (pageIndex - 1)).ToList();
            ViewData["total"] = projectDevelopTaskBookRepository.GetModel(r => r.PROJECT_ID == proId).Count();
            ViewBag.ProjectId = projectId;
            PROJECT_DEVELOP project = projectDevelopRepository.GetModel(r => r.PROJECT_DEVELOP_ID == proId).FirstOrDefault();
            ViewBag.ProjectName = project.PROJECT_NAME;
            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;
            List<ProjectTaskBookViewModel> model = new List<ProjectTaskBookViewModel>();

            for (int i = 0; i < taskBookList.Count; i++)
            {
                Guid userId = taskBookList[i].CREATER;
                string showName = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;
                ProjectTaskBookViewModel item = new ProjectTaskBookViewModel();
                item.TaskBookContext = taskBookList[i].TASKBOOK_CONTEXT;
                item.TaskBookCreateTime = taskBookList[i].CREATE_TIME.ToString("yyyy-MM-dd");
                item.TaskBookId = taskBookList[i].TASKBOOK_ID;
                item.TaskBookName = taskBookList[i].TASKBOOK_NAME;
                item.Creater = showName;
                model.Add(item);
            }

            return this.View(model);
        }

        [HttpPost]
        public JsonResult GetTaskBookInfo(Guid taskBookId)
        {
            
            PROJECT_DEVELOP_TASKBOOK taskBook = projectDevelopTaskBookRepository.GetModel(r => r.TASKBOOK_ID == taskBookId).FirstOrDefault();
            FILEINFO file =
                fileRepository.GetModel(r => r.FILE_TYPE == "DEVELOP_TASKBOOK" && r.CONTACT_ID == taskBookId)
                    .FirstOrDefault();

            Guid userId = taskBook.CREATER;
            string showName = userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME;

            ProjectTaskBookViewModel model = new ProjectTaskBookViewModel();
            model.Creater = showName;
            model.TaskBookContext = taskBook.TASKBOOK_CONTEXT;
            model.TaskBookCreateTime = taskBook.CREATE_TIME.ToString("yyyy-MM-dd");
            model.TaskBookName = taskBook.TASKBOOK_NAME;
            if (file != null && file.FILE_ID.ToString().Trim() != "")
            {
                model.TaskBookFileId = file.FILE_ID;
                model.TaskBookFilePath = file.FILE_SAVEPATH;
                model.TaskBookFileSaveName = file.FILE_SAVENAME;
                model.TaskBookFileShowName = file.FILE_SHOWNAME;
            }
            else
            {
                //model.TaskBookFileId = file.FILE_ID;
                model.TaskBookFilePath = "";
                model.TaskBookFileSaveName = "";
                model.TaskBookFileShowName = "";
            }

            //ViewBag.CreateTaskBookModel = model;

            return this.Json(model);

        }

        [HttpPost]
        public ActionResult CreateTaskBook(FormCollection collection)
        {
            PROJECT_DEVELOP_TASKBOOK taskBookModel=new PROJECT_DEVELOP_TASKBOOK();
            FILEINFO fileModel=new FILEINFO();
            taskBookModel.TASKBOOK_ID = Guid.NewGuid();
            taskBookModel.PROJECT_ID = new Guid(collection["hid_ProjectId"]);
            taskBookModel.TASKBOOK_NAME = collection["tb_TaskBookName"];
            taskBookModel.CREATER = new Guid(CurrentUser.UserID);
            taskBookModel.TASKBOOK_CONTEXT = collection["tb_TaskBookContext"];
            taskBookModel.CREATE_TIME = DateTime.Now;
            string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\TaskBook\";
            int fileCount = this.Request.Files.Count;

            HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];
            this.Request.Files.CopyTo(upFiles, 0);
            if (upFiles[0].FileName!="")
            {
                try
                {
                    string fileSaveName = string.Empty;
                    HttpPostedFile hpf;
                    hpf = upFiles[0];
                    string fullUpLoadPath = "";
                    Guid fileName = Guid.NewGuid();
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));

                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length-1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASKBOOK";
                    fileModel.CONTACT_ID = taskBookModel.TASKBOOK_ID;

                    fileRepository.Insert(fileModel);
                    
                }
                catch (Exception ex)
                {
                    LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书新增失败！ 信息：" + ex.Message);

                    return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "CreateFalse", flagInfo = ex.Message, projectId = taskBookModel.PROJECT_ID });
                }
            }
            try
            {

                projectDevelopTaskBookRepository.Insert(taskBookModel);
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书新增成功！");

                return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea",flag="CreateTrue", projectId = taskBookModel.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书新增失败！ 信息：" + ex.Message);


                return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "CreateFalse", flagInfo=ex.Message, projectId = taskBookModel.PROJECT_ID });
            }
        }

        [HttpPost]
        public ActionResult EditTaskBook(FormCollection collection)
        {
            Guid taskBookId = new Guid(collection["hid_EditTaskBookId"]);
            PROJECT_DEVELOP_TASKBOOK taskBookModel =
                projectDevelopTaskBookRepository.GetModel(r => r.TASKBOOK_ID == taskBookId).FirstOrDefault();
            FILEINFO fileModel = new FILEINFO();
            string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\TaskBook\";

            #region 获取界面数据

            try
            {
                //taskBookModel.TASKBOOK_ID = Guid.NewGuid();
                //taskBookModel.PROJECT_ID = new Guid(collection["hid_ProjectId"]);
                taskBookModel.TASKBOOK_NAME = collection["tb_TaskBookName"] == "" ? taskBookModel.TASKBOOK_NAME : collection["tb_TaskBookName"];
                taskBookModel.CREATER = new Guid(CurrentUser.UserID);
                taskBookModel.TASKBOOK_CONTEXT = collection["tb_TaskBookContext"] == "" ? taskBookModel.TASKBOOK_CONTEXT : collection["tb_TaskBookContext"];
                taskBookModel.CREATE_TIME = DateTime.Now;

            }
            catch (Exception ex)
            {
                return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskBookModel.PROJECT_ID });
            }

            #endregion

            int fileCount = this.Request.Files.Count;

            HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];
            this.Request.Files.CopyTo(upFiles, 0);
            if (upFiles[0].FileName != "")
            {
                #region 删除旧文件记录

                try
                {
                    FILEINFO oldFile =
                        fileRepository.GetModel(r => r.CONTACT_ID == taskBookId && r.FILE_TYPE == "DEVELOP_TASKBOOK").FirstOrDefault();
                    fileRepository.Delete(oldFile);
                }
                catch (Exception ex)
                {
                    return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskBookModel.PROJECT_ID });
                }


                #endregion

                #region 上传新文件 并向数据库中插入数据

                try
                {
                    string fileSaveName = string.Empty;
                    HttpPostedFile hpf;
                    hpf = upFiles[0];
                    string fullUpLoadPath = "";
                    Guid fileName = Guid.NewGuid();
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));

                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASKBOOK";
                    fileModel.CONTACT_ID = taskBookModel.TASKBOOK_ID;
                    fileRepository.Insert(fileModel);

                }
                catch (Exception ex)
                {
                    LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书编辑失败！ 信息：" + ex.Message);

                    return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskBookModel.PROJECT_ID });
                }

                #endregion
            }
            try
            {
                projectDevelopTaskBookRepository.Update(taskBookModel);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书编辑成功！");

                return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "EditTrue", projectId = taskBookModel.PROJECT_ID });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书编辑失败！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "EditFalse", flagInfo = ex.Message, projectId = taskBookModel.PROJECT_ID });
            }
        }

        [HttpGet]
        public ActionResult DeleteTaskBook(Guid taskBookId)
        {
            PROJECT_DEVELOP_TASKBOOK model= projectDevelopTaskBookRepository.GetModel(r => r.TASKBOOK_ID == taskBookId).FirstOrDefault();
            Guid  proId = model.PROJECT_ID;
            FILEINFO file =
                fileRepository.GetModel(r => r.CONTACT_ID == taskBookId && r.FILE_TYPE == "DEVELOP_TASKBOOK")
                    .FirstOrDefault();

            try
            {
                projectDevelopTaskBookRepository.Delete(model);
                if (file != null && file.FILE_ID.ToString()!="")
                {
                    fileRepository.Delete(file);
                }

                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书编辑删除！");

                return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "DelTrue", projectId = proId });

            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "任务书编辑删除！ 信息：" + ex.Message);

                return RedirectToAction("ProjectTaskBookList", "TaskBook", new { area = "DevelopArea", flag = "DelFalse", flagInfo = ex.Message, projectId = proId });
            }


        }

    }
}